/**
 * myEvent.trigger 事件触发
 * myEvent.on 事件监听
 * myEvent.off 指定事件移除
 * myEvent.offAll 所有事件移除
 */
define(function() {
	function EventDispatcher() {
		this.listeners = [];
	}

	/*事件触发*/
	EventDispatcher.prototype.trigger = function(eventName, data) {
		var self = this;
		var fn = self.listeners[eventName] || null;
		var i;
		if (fn instanceof Array) {
			for (i = 0; i < fn.length; i++) {
				if (fn[i]) {
					fn[i](eventName, data);
				}
			}
		} else if (fn instanceof Function) {
			fn && fn(eventName, data);
		}
	}

	/*事件监听*/
	EventDispatcher.prototype.on = function(eventName, fun) {
		var self = this;
		var fnArr = self.listeners[eventName] || null;
		if (fun instanceof Function) {
			if (fnArr instanceof Array) {
				fnArr.push(fun);
			} else if (fnArr instanceof Function) {
				var oldFn = fnArr;
				fnArr = [];
				fnArr.push(oldFn);
				fnArr.push(fun);
				self.listeners[eventName] = fnArr;
			} else if (fnArr == null) {
				self.listeners[eventName] = fun;
			}
		}
	}

	/*指定事件移除*/
	EventDispatcher.prototype.off = function(eventName, fun) {
		var self = this;
		var fnArr = self.listeners[eventName] || null;
		if (fnArr) {
			if (!fun) {
				delete self.listeners[eventName];
				return;
			}
			if (fnArr instanceof Function) {
				if (fnArr == fun) {
					delete self.listeners[eventName]
				}
			} else if (fnArr instanceof Array) {
				for (var i = 0; i < fnArr.length; i++) {
					if (fnArr[i] == fun) {
						fnArr.splice(i, 1);
						break;
					}
				}
			}
		}
	}

	/*所有事件移除*/
	EventDispatcher.prototype.offAll = function() {
		var self = this;
		self.listeners = [];
	}

	return EventDispatcher;
})